//
//  JHAssetsPhotoPickerViewControllerm
//  JHAssetsPhotoPickerViewController
//
//  Created by admin on 15/11/16.
//  Copyright © 2015年 mohe. All rights reserved.
//

#import "JHAssetsPhotoPickerViewController.h"
#import "JHAssetsCollectionCell.h"
#import "JHAssetsGirdViewController.h"
#import "JHAssetsManager.h"

static NSString * const cellReuseIdentifier = @"collectionCell";

@interface JHAssetsPhotoPickerViewController ()
{
    BOOL viewIsActive;
}
@end

@implementation JHAssetsPhotoPickerViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if(!viewIsActive){
        [self tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        
        viewIsActive = YES;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView registerClass:[JHAssetsCollectionCell class] forCellReuseIdentifier:cellReuseIdentifier];
    [self.tableView setRowHeight:kGroupCellHeight];
    [self.tableView setTableFooterView:[[UIView alloc] init]];
    [self setTitle:@"相册"];
    [self loadCollection];
    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(dismissPickViewController)];
    self.navigationItem.rightBarButtonItem = cancelItem;
}
//加载相册中的分组数据
- (void)loadCollection{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        self.collectionResults = [NSArray arrayWithArray:[JHAssetsCollectionManager loadCollections]];
            dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma makr - getter
- (JHAssetsSetting *)setting
{
    if(_setting){
        return _setting;
    }
    _setting =[[JHAssetsSetting alloc]init];
    return _setting;
}
#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.collectionResults.count + 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JHAssetsCollectionCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier forIndexPath:indexPath];
    if(indexPath.row){
        PHAssetCollection *collection = self.collectionResults[indexPath.row-1];
        JHAssetsCollectionManager *manager = [JHAssetsCollectionManager defaultManager];
        
        //设置相册标题
        [cell.titleView setText:collection.localizedTitle];
        //设置相册中资源的数量
        if(collection.estimatedAssetCount == NSNotFound){
            [cell.numberLabel setText:[NSString stringWithFormat:@"%lu%@", [manager getCountOfCollection:collection], [self.setting unitDescribe]]];
        }else{
            [cell.numberLabel setText:[NSString stringWithFormat:@"%lu%@", collection.estimatedAssetCount,[self.setting unitDescribe]]];
        }
    }else{


        PHFetchResult *arr = [self getAllAssets];
        [cell.titleView setText:[NSString stringWithFormat:@"全部%@", [self.setting assetsDescribe]]];
         [cell.numberLabel setText:[NSString stringWithFormat:@"%lu%@",arr.count,[self.setting unitDescribe]]];
    }
    

    return cell;
}
- (PHFetchResult *)getAllAssets
{
    PHAssetMediaType type = PHAssetMediaTypeImage;
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
    
    PHFetchResult *arr = [PHAsset fetchAssetsWithMediaType:type options:options];
    return arr;
}
#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView willDisplayCell:(JHAssetsCollectionCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row){
        PHAssetCollection *collection = self.collectionResults[indexPath.row-1];
        //设置相册封面图片
        JHAssetsCollectionManager *manager = [JHAssetsCollectionManager defaultManager];
        PHAsset *asset = [manager getCoverImageWithCollection:collection];
        cell.representedAssetIdentifier = collection.localIdentifier;
        [[JHAssetsManager defaultManager] thumbnailWithAsset:asset size:cell.coverImageView.frame.size completion:^(UIImage *image) {
            if ([cell.representedAssetIdentifier isEqualToString:collection.localIdentifier]) {
                [cell.coverImageView setImage:image];
            }
        }];
    }else{
        PHFetchResult *fetchResult = [self getAllAssets];
        if(fetchResult.count > 0){
            PHAsset *asset = [fetchResult firstObject];
            cell.representedAssetIdentifier = @"allAssets";
            [[JHAssetsManager defaultManager] thumbnailWithAsset:asset size:cell.coverImageView.frame.size completion:^(UIImage *image) {
                if ([cell.representedAssetIdentifier isEqualToString:@"allAssets"]) {
                    [cell.coverImageView setImage:image];
                }
            }];
        }
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    JHAssetsGirdViewController *vc = [[JHAssetsGirdViewController alloc]initWithNibName:@"JHAssetsGirdViewController" bundle:nil];
    vc.picker = self;
    if(indexPath.row){
        PHAssetCollection *collection = self.collectionResults[indexPath.row-1];
        [vc setTitle:collection.localizedTitle];
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
        vc.assetResults = [PHAsset fetchAssetsInAssetCollection:collection options:options];
    }else{
        [vc setTitle:[NSString stringWithFormat:@"全部%@", [self.setting assetsDescribe]]];
        vc.assetResults = [self getAllAssets];
    }
    vc.setting = self.setting;
    [self.navigationController pushViewController:vc animated:viewIsActive];
}
- (void)dismissPickViewController
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    if(self.delegate && [self.delegate respondsToSelector:@selector(photoPicker:didSelecteFiniehed:)]){
        [self.delegate photoPicker:self didSelecteFiniehed:nil];
    }
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
